<template>
    <el-container class="groupPerson_container">
        <vAside ref="aside" :options="asideOptions" :treeOptions="treeOptions"
                :treeData="treeData" @event="handleAsideEvent">
            <template slot="button">
                <i class="ml5 el-icon-circle-plus-outline"
                   v-permission="'system:group:save'"
                   @click="handleType(null, null, 'add')"></i>
                <el-tooltip class="item" effect="dark" content="全部员工" placement="top">
                    <i class="ml10 fa fa-list-ul"
                       :style="treeData.length && !treeNodeKey.sid ? 'color:#409EFf' : ''"
                       @click="getAllList()"></i>
                </el-tooltip>
            </template>
        </vAside>
        <el-main>
            <el-card class="box-card">
                <headerTemplate slot="header" ref="header"
                                :table-ref="tableOptions.ref"
                                :toolbar_buttons="toolbar_buttons"
                                :toolbar_filter="toolbar_filter"
                                :searchForm="searchForm"
                                title="模糊搜索工号、姓名、电话、电子邮件"
                                @event="handleEvent" />
                <vxeTableTemplate :data="dataList" :options="tableOptions"
                                  @event="handleTableEvent" />
            </el-card>
            <!-- 部门弹框 -->
            <el-dialog
                :title="dialogOption.title"
                :visible.sync="dialogOption.visible"
                width="400px"
                destroy-on-close
                v-dialogDrag
            >
                <el-form
                    ref="groupForm"
                    :rules="rules"
                    :model="groupForm"
                    label-width="100px"
                >
                    <el-form-item label="名称" prop="name">
                        <el-input
                            v-model="groupForm.name"
                            autocomplete="off"
                            clearable
                            placeholder="请输入名称"
                        ></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogOption.visible = false">取 消</el-button>
                    <el-button type="primary" @click="saveGroup" v-btnLoading
                    >确 定
                    </el-button
                    >
                </div>
            </el-dialog>
            <groupPersonDialog
                ref="groupPersonDialog"
                :treeNodeKey="treeNodeKey"
                :options="groupPersonDialogOption"
                :treeData="treeData"
                @event="handleEvent"
            ></groupPersonDialog>
        </el-main>
    </el-container>
</template>

<script>
import sysGroupPersonApi from "@common/api/system/sysGroupPersonApi";
import groupPersonDialog from "../dialog/GroupPerson";
import provide from "@common/mixins/provide";

export default {
    extends: provide,
    name: "SysGroupPerson",
    components: { groupPersonDialog },
    data() {
        let $this = this;
        return {
            checked: true,
            isShrink: true,
            toolbar_buttons: [
                {
                    id: "refresh",
                    icon: "fa fa-refresh",
                    show: true,
                    method: () => {
                        $this.getList();
                    },
                },
                {
                    id: "add",
                    type: "primary",
                    icon: "fa fa-plus",
                    show: true,
                    permission: 'system:groupPerson:save',
                    method: () => {
                        $this.open(null, "add");
                    },
                },
                {
                    id: "edit",
                    type: "success",
                    icon: "fa fa-pencil",
                    show: true,
                    permission: 'system:groupPerson:save',
                    method: () => {
                        $this.open(null, "edit");
                    },
                },
                {
                    id: "del",
                    type: "danger",
                    icon: "fa fa-trash-o",
                    show: true,
                    permission: 'system:groupPerson:delete',
                    method: () => {
                        $this.open(null, "del");
                    },
                },
            ], //左侧按钮
            toolbar_filter: [
                // { type: "text", field: "number", label: "编码" },
                // { type: "text", field: "name", label: "名称" },
            ], //精确筛选
            dataList: [],
            tableOptions: {
                ref: "clientsTable",
                container: ".groupPerson_container",
                multiSelect: true,
                checkboxConfig: {
                    visibleMethod({ row }) {
                        return row.full_code !== 'admin';
                    },
                    checkMethod({ row }) {
                        return row.full_code !== 'admin';
                    },
                },
                columns: [
                    {
                        label: "工号",
                        prop: "code",
                        align: "center",
                    },
                    {
                        label: "姓名",
                        prop: "name",
                        align: "center",
                    },
                    {
                        label: "性别",
                        prop: "sex",
                        align: "center",
                        formatter: (row) => {
                            if (row.sex === 2) {
                                return "女";
                            } else if (row.sex === 1) {
                                return "男";
                            } else return "";
                        },
                    },
                    {
                        label: "生日",
                        prop: "birth_day",
                        align: "center",
                        width: 150,
                    },
                    {
                        label: "电话",
                        prop: "phone",
                        align: "center",
                        width: 150,
                    },
                    {
                        label: "电子邮件",
                        prop: "email",
                        align: "center",
                        width: 150,
                    },
                    {
                        label: "所属部门",
                        prop: "group_name",
                        align: "center",
                        width: 150,
                    },
                    {
                        label: "绑定账户",
                        prop: "user_name",
                        align: "center",
                        width: 150,
                    },
                ],
                operates: {
                    // width: 150,
                    fixed: "right",
                    list: [
                        {
                            id: "preview",
                            icon: "fa fa-qrcode",
                            type: "primary",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "二维码",
                            },
                            permission: 'system:groupPerson:qrcode',
                            method: (index, row) => {
                                $this.openPreviewDialog(row);
                            },
                        },
                        {
                            id: "edit",
                            icon: "fa fa-pencil",
                            show: true,
                            type: "success",
                            tooltip: {
                                content: "编辑",
                            },
                            permission: 'system:groupPerson:save',
                            method: (key, row, index) => {
                                $this.open(row, "edit");
                            },
                        },
                        {
                            id: "info",
                            icon: "fa fa-trash-o",
                            type: "danger",
                            tooltip: {
                                content: "删除",
                            },
                            permission: 'system:groupPerson:delete',
                            show: true,
                            filter(row) {
                                return row.full_code !== 'admin';
                            },
                            method: (key, row, index) => {
                                $this.open(row, "del");
                            },
                        },
                    ],
                },
                pagination: {
                    pageIndex: 1,
                },
            },
            searchForm: {},
            selectionList: [],
            treeOptions: {
                ref: "$checkTree",
                highlightCurrent: true,
                defaultExpandAll: true,
                props: {
                    label: "name",
                    children: "childrens",
                },
                buttons: [
                    {
                        icon: "el-icon-circle-plus-outline",
                        permission: 'system:group:save',
                        filter(data) {
                            return data.sid !== '-1';
                        },
                        method: (data, $event) => {
                            $this.handleType(data, $event, "add");
                        },
                    },
                    {
                        icon: "fa fa-pencil",
                        permission: 'system:group:save',
                        filter(data) {
                            return data.sid !== '-1';
                        },
                        method: (data, $event) => {
                            $this.handleType(data, $event, "edit");
                        },
                    },
                    {
                        icon: "fa fa-trash-o",
                        permission: 'system:group:delete',
                        filter(data) {
                            return data.sid !== '-1';
                        },
                        method: (data, $event) => {
                            $this.handleType(data, $event, "del");
                        },
                    },
                ], //右侧按钮
            },
            treeData: [],
            asideOptions: {
                width: "300px",
                title: "部门",
            },
            //弹窗option
            dialogOption: {
                visible: false,
            },
            //员工弹窗option
            groupPersonDialogOption: {
                visible: false,
            },
            rules: {
                name: [
                    { required: true, message: "请输入名称", trigger: "blur" },
                    //目前只兼容中文、大小写英文、数字
                    {
                        // pattern: /^[A-Za-z0-9\u4e00-\u9fa5]{1,50}$/,
                        // message:
                        //   "最大 50 位大小写英文、数字或者其它地区语言字符，不能包含特殊字符",
                        max: 50,
                        message: "最大 50 位字符，内容过长，请删减",
                        trigger: "blur",
                    },
                ],
            },
            //编辑新增的form数据
            groupForm: {},
            treeNodeKey: {}, //当前选中树节点
            previewVisible: false, //二维码弹框
        };
    },
    watch: {},
    mounted() {
        // this.getList();
        this.getTreeData();
    },
    methods: {
        // 全部按钮点击事件
        getAllList() {
            let $this = this;
            $this.treeNodeKey = {};
            $this.$checkTree && $this.$checkTree.setCurrentKey(null);
            $this.tableOptions.pagination.pageIndex = 1;
            $this.getList();
        },
        // 分类树按钮点击事件
        handleType(data, event, type) {
            if (event) event.stopPropagation();
            let $this = this;
            let title = type === "add" ? "创建" : "编辑";
            if (type === "edit") {
                if ($this.$utils.isNotEmpty(data)) {
                    $this.groupForm = {
                        id: data.id,
                        name: data.name,
                    };
                }
            } else if (type === "add") {
                $this.groupForm = {};
                $this.groupForm.parent_sid = data ? data.sid : 'root';
            } else if (type === "del") {
                this.handleClientTypeConfirm(data);
                return;
            }
            $this.dialogOption = $.extend({}, $this.dialogOption, {
                title: title,
                visible: true,
            });
        },
        // 分类删除确认
        handleClientTypeConfirm(data) {
            let sid = data.sid;
            let $this = this;
            if (data.childrens && data.childrens.length) {
                return $this.$message.warning("存在下级分类，请先删除下级分类");
            }
            $this.$confirm("是否确认删除分类，分类下的数据也会删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                sysGroupPersonApi.deleteSysGroup({ sids: [sid] }, () => {
                    if (sid === data.id) {
                        $this.treeNodeKey = {};
                    }
                    $this.getTreeData();
                    $this.$message.success("删除成功");
                });
            }).catch(() => {
            });
        },
        // 保存分类
        saveGroup() {
            let $this = this;
            $this.$refs["groupForm"].validate((valid) => {
                if (valid) {
                    sysGroupPersonApi.saveSysGroup($this.groupForm, () => {
                        $this.dialogOption = $.extend({}, $this.dialogOption, {
                            visible: false,
                        });
                        $this.$message.success("保存成功！");
                        $this.getTreeData();
                    });
                } else {
                    return false;
                }
            });
        },
        // 接收当前点击分类
        handleAsideEvent(event) {
            let $this = this;
            if (event.type === "nodeClick") {
                $this.treeNodeKey = event.data;
                $this.getList();
            }
        },
        // 接收搜索条件
        handleEvent(event) {
            let _this = this;
            _this.searchForm = $.extend({}, _this.searchForm, event.searchForm);
            if (event.type === "search") {
                _this.getList(true);
            } else if (event.type === "refresh") {
                _this.getList(true);
            }
        },
        // 获取分类树的数据
        getTreeData() {
            let $this = this;
            let queryData = {};
            sysGroupPersonApi.findSysGroupTreeAll(queryData, (result) => {
                $this.treeData = result.data || [];
                if ($this.treeNodeKey.id) {
                    $this.$nextTick(() => {
                        $this.$checkTree.setCurrentKey($this.treeNodeKey.id);
                    });
                } else if ($this.treeData && $this.treeData.length > 0) {
                    $this.$nextTick(() => {
                        $this.$checkTree.setCurrentKey($this.treeData[0].id);
                        $this.treeNodeKey = $this.treeData[0];
                        $this.getList();
                    });
                }
            });
        },
        // 行点击事件，并修改值
        saveRow(row) {
            let $this = this;
            sysGroupPersonApi.saveSysClient(row, (result) => {
                $this.$message.success("保存成功！");
            });
        },
        rowCopy(row) {
            let $this = this;
            let arr = [];
            $this.tableOptions.columns.forEach((item) => {
                if (item.prop !== "state") arr.push(row[item.prop]);
            });
            let Str = arr.join(" ");
            if ($this.$XEUtils.stringCopy(Str)) {
                $this.$message.success("复制成功！");
            } else {
                $this.$message.success("复制失败");
            }
        },
        // 获取客户列表
        getList(search) {
            let $this = this;
            let queryData = {};
            $this.dataList = [];
            if (search) {
                $this.tableOptions = $this.resetTablePagination($this.tableOptions);
            }
            queryData = Object.assign({}, $this.searchForm);
            // if ($this.treeNodeKey.parentSid && $this.treeNodeKey.sid) {
            if ($this.treeNodeKey.sid) {
                queryData.group_sid = $this.treeNodeKey.sid;
            }
            queryData = $this.getQueryParams($this.tableOptions, queryData);
            sysGroupPersonApi.findSysGroupPersons(queryData, (result) => {
                $this.dataList = result.data || [];
                $this.tableOptions = $this.setTableTotal($this.tableOptions, result);
            });
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        //新增/编辑
        open(row, type) {
            let $this = this;
            let ids = [];
            let title;
            if (type === "add") {
                title = "创建";
                row = {
                    sex: 1,
                    group_sid: this.treeNodeKey.sid || null,
                };
            } else {
                title = "编辑";
                if (!row) {
                    //判断当前操作是多选还是单选
                    row = this.selectionList;
                    if (row.length === 0) {
                        return $this.$message.error("请选中一条数据");
                    }
                    if (type === "edit") {
                        if (row.length > 1) {
                            return $this.$message.error("不能同时编辑多条数据");
                        } else [ row ] = row;
                    } else if (type === "del") {
                        ids = row.map((item) => item.id);
                    }
                } else {
                    if (type === "del") {
                        ids.push(row.id);
                    } else if (type === "edit") {
                        $this.assistForm = row;
                    }
                }
                if (ids.length) return $this.confirmDel(ids);
            }
            if (type === "add") {
                if (!$this.treeNodeKey.sid) {
                    return $this.$message.error("请先选择部门");
                }
            }
            $this.$refs.groupPersonDialog.openDialog(row, type);
            // $this.groupPersonDialogOption = $.extend(
            //   {},
            //   $this.groupPersonDialogOption,
            //   {
            //     title: title,
            //     visible: true,
            //   }
            // );
        },
        // 确认删除用户
        confirmDel(ids) {
            let $this = this;
            $this.$confirm("是否继续删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                sysGroupPersonApi.batchDeleteSysGroupPerson({ id_list: ids }, () => {
                    $this.getList();
                    $this.$message.success("删除成功");
                    $this.$bus.$emit('updateSystemDashboard');
                });
            }).catch(() => {
            });
        },
        // 打开预览打印弹框
        openPreviewDialog(row) {
            let $this = this;
            $this.$QRCode({
                width: '500px',
                data: [
                    {
                        sid: row.sid,
                        text: row.code,
                        tip: '二维码的值格式是：员工工号',
                    }
                ],
                pageStyle: {
                    justifyContent: 'center',
                },
                showDownload: true,
            });
        },
        // 打印二维码
        printQrCode() {
            this.$print(this.$refs.print);
        },
        // 下载二维码
        saveQrCode() {
            //找到canvas标签
            let myCanvas = document
            .getElementById("print")
            .getElementsByTagName("canvas");
            let img = document.getElementById("print").getElementsByTagName("img");
            // // //创建一个a标签节点
            let a = document.createElement("a");
            // //设置a标签的href属性（将canvas变成png图片）
            let imgURL = myCanvas[0].toDataURL("image/jpg");
            let ua = navigator.userAgent;
            if (ua.indexOf("Trident") != -1 && ua.indexOf("Windows") != -1) {
                // IE内核 并且  windows系统 情况下 才执行;
                var bstr = atob(imgURL.split(",")[1]);
                var n = bstr.length;
                var u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                var blob = new Blob([ u8arr ]);
                window.navigator.msSaveOrOpenBlob(blob, "二维码" + "." + "png");
            } else if (ua.indexOf("Firefox") > -1) {
                //火狐兼容下载
                let blob = this.base64ToBlob(imgURL); //new Blob([content]);
                let evt = document.createEvent("HTMLEvents");
                evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
                a.download = " "; //下载图片名称，如果填内容识别不到，下载为未知文件，所以我这里就不填为空
                a.href = URL.createObjectURL(blob);
                a.dispatchEvent(
                    new MouseEvent("click", {
                        bubbles: true,
                        cancelable: true,
                        view: window,
                    })
                ); //兼容火狐
            } else {
                //谷歌兼容下载
                img.src = myCanvas[0].toDataURL("image/jpg");
                // a.href = myCanvas[0].toDataURL('image/png').replace('image/png', 'image/octet-stream')
                a.href = img.src;
                //设置下载文件的名字
                a.download = "二维码";
                //点击
                a.click();
            }
        },
        //base64转blob
        base64ToBlob(code) {
            let parts = code.split(";base64,");
            let contentType = parts[0].split(":")[1];
            let raw = window.atob(parts[1]);
            let rawLength = raw.length;
            let uInt8Array = new Uint8Array(rawLength);
            for (let i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i);
            }
            return new Blob([ uInt8Array ], { type: contentType });
        },
    },
};
</script>
